import "./index.scss"
import {View, Text} from "@tarojs/components"
import {observer} from "mobx-react"
import {useContext, useEffect, useState} from "react"
import {useDidHide, useDidShow, useRouter} from "@tarojs/taro"
import {devControllStore} from "./model"
import {uSelectDevControl, exeControlCommand} from "@/api/setting"
import {ControllBtn} from "./components"
import Middlevare from "./middleware"
import Taro from "@tarojs/taro"

const Devcontroll = () => {
	let router = useRouter()
	const {updatePageQuery, clearPageQuery, pageQuery} = useContext(devControllStore)

	const [dataSource, setDataSource] = useState<Setting.DevControll[]>([])

	/* 存储组件模块的数据 */
	const [compModuleData, setCompModuleData] = useState([])

	function updatePageDataSource(isReadR = false) {
		//  Taro.showLoading({
		//    title: '加载中'
		//  })
		if (!pageQuery.devId) return
		uSelectDevControl({
			devId: pageQuery.devId
		})
			.then(res => {
				console.log(res.data, "res.data")
				let nData = []
				res.data.forEach((item, index) => {
					if (nData.length == 0) {
						console.log(index, "indexif")
						let obj = {
							list: []
						}
						obj.list.push(item)
						nData.push(obj)
					} else {
						console.log(index, "indexelse")
						if (item.typeFlag == "2" || item.typeFlag == "3") {
							if (item.typeFlag == "2") {
								nData[nData.length - 1].list.push(item)
							} else if (item.typeFlag == "3") {
								if (
									nData[nData.length - 1].list[
										nData[nData.length - 1].list.length - 1
									].typeFlag != "3"
								) {
									let obj = {
										list: []
									}
									obj.list.push(item)
									nData.push(obj)
								} else {
									nData[nData.length - 1].list.push(item)
								}
							}
						} else {
							let obj = {
								list: []
							}
							obj.list.push(item)
							nData.push(obj)
						}
						// nData.forEach(item2 => {
						// 	if (item.typeFlag == "2" && item2.list.length < 2) {
						// 		console.log(item, "同上")

						//
						// 	} else {
						//
						//
						//
						// 	}
						// })
					}
				})
				console.log(nData, "nData")
				// let newData = []
				// nData.forEach((item, index) => {
				// 	if (index >= 4) {
				// 		newData.push(item)
				// 	}
				// })
				// console.log(newData, "nData")
				setCompModuleData(nData)
			})
			.catch(err => {
				setDataSource([])
			})

		// 页面刚开始查询状态
		// exeControlCommand({
		//   controlId:4
		// }).then(res =>{
		//   if(res.msg=='开启中'){
		//     setRainwaterChecked(true)
		//   }else{
		//     setRainwaterChecked(false)
		//   }
		// })

		const newarr = [
			{
				controlId: 1,
				controlCode: "001",
				controlName: "001",
				devId: 1,
				DevControll: "001"
			},
			{
				controlId: 2,
				controlCode: "002",
				controlName: "002",
				devId: 2,
				DevControll: "001"
			},
			{
				controlId: 3,
				controlCode: "003",
				controlName: "003",
				devId: 3,
				DevControll: "001"
			},
			{
				controlId: 4,
				controlCode: "004",
				controlName: "004",
				devId: 4,
				DevControll: "001"
			}
		]

		// setDataSource(newarr)
	}

	// 可以使用所有的 React Hooks
	useEffect(() => {
		console.log("Devcontroll useEffect dataSource", dataSource)

		// setTimeout(() => {

		// }, 1000)
	}, [dataSource])

	// 可以使用所有的 React Hooks
	useEffect(() => {
		console.log("Devcontroll useEffect")
		updatePageDataSource(false)
	}, [pageQuery])
	// 对应 onShow
	useDidShow(() => {
		console.log("Devcontroll useDidShow")
		updatePageQuery(router.params)
		// updatePageDataSource(false)
	})
	// 对应 onHide
	useDidHide(() => {
		console.log("Devcontroll useDidHide")
		clearPageQuery()
	})

	// 是否有读取状态
	const [isRead, setIsRead] = useState(false)

	// 读取指令存储
	const [readOrderList, setReadOrderList] = useState([])

	// 当前雨水开关的标识
	const [rainwaterChecked, setRainwaterChecked] = useState(false)
	// 当前污水开关的标识
	const [sewageChecked, setSewageChecked] = useState(false)

	// 雨水---开指令ID
	const [rainwaterOpen, setRainwaterOpen] = useState(0)
	// 雨水---关指令ID
	const [rainwaterClose, setRainwaterClose] = useState(0)
	// 雨水---开指令ID
	const [sewageOpen, setSewageOpen] = useState(0)
	// 雨水---关指令ID
	const [sewageClose, setSewageClose] = useState(0)

	// 单个开关的指令
	const [oneOpenSwitch, setOneOpenSwitch] = useState(0)
	const [oneCancelSwitch, setOneCancelSwitch] = useState(0)

	// 单个按钮当前是开还是关的标识
	const [oneSwichStatus, setOneSwitchStatus] = useState(false)

	// 判断是单个开关，或者是两个开关的请求的标识
	const [oneOrTwoSwitch, setOneOrTwoSwitch] = useState(false)

	// 判断是开关还是按钮的标识
	const [isSwitchOrBtn, setIsSwitchOrBtn] = useState(true)

	// 单个只开启卡片的是开启还是关闭的状态标识     默认关闭  开启之后不可关闭  再次点击也是关闭状态
	// const [isOnlyOpenCardState, setIsOnlyOpenCardState] = useState(true)

	// 单个只开启卡片点击开始的点击事件
	// const onlyOpenCardClick = () => {
	//   console.log(isOnlyOpenCardState)
	// }
	// 单个只开启卡片点击开始的指令
	const [oneOnlyEnabledInstruction, setOneOnlyEnabledInstruction] = useState(0)

	// 单个只开启卡片点击开始的点击事件
	// const onlyOpenCardClick = async (controll: object) => {
	// 	console.log(controll)
	// 	let openControlId = 0
	// 	let openControlName = controll.funName

	// 	controll.data.forEach(item => {
	// 		if (item.status != 0) {
	// 			switch (item.makeProperty) {
	// 				case "open":
	// 					openControlId = item.controlId
	// 					break

	// 				default:
	// 					break
	// 			}
	// 		}
	// 	})
	// 	console.log(openControlId)

	// 	Taro.showModal({
	// 		title: "提示",
	// 		content: `确定要启动${openControlName}检测吗?`,
	// 		async success(result) {
	// 			Taro.showLoading({
	// 				title: "执行中..."
	// 			})
	// 			if (result.confirm) {
	// 				await exeControlCommand({controlId: openControlId})
	// 					.then(res => {
	// 						if (res.result == "error") {
	// 							Taro.showToast({
	// 								title: res.msg,
	// 								icon: "error"
	// 							})
	// 						} else {
	// 							console.log(res)
	// 							Taro.hideLoading()
	// 							Taro.showToast({
	// 								title: "启动完成!"
	// 							})
	// 							updatePageDataSource()
	// 						}

	// 						// if (res.result == 'error') {
	// 						//   Taro.showToast({
	// 						//     title: res.msg
	// 						//   })
	// 						// } else {
	// 						//   Taro.showToast({
	// 						//     title: '启动完成!'
	// 						//   })
	// 						// }
	// 					})
	// 					.catch(err => {
	// 						Taro.hideLoading()
	// 						Taro.showToast({
	// 							title: err.msg
	// 						})
	// 					})
	// 			} else if (result.cancel) {
	// 				Taro.hideLoading()
	// 			}
	// 		}
	// 	})
	// }

	// 发送指令错误提示函数
	function instructErrorHintFunc() {
		Taro.showModal({
			title: "提示",
			content: `设备不在线，无法执行！`,
			success(result) {
				if (result.confirm) {
				} else if (result.cancel) {
				}
			}
		})
		setRainwaterChecked(!rainwaterChecked)
		setSewageChecked(!sewageChecked)
		setRainwaterChecked(rainwaterChecked)
		setSewageChecked(sewageChecked)
		setOneSwitchStatus(!oneSwichStatus)
		setOneSwitchStatus(oneSwichStatus)
	}

	// 控制雨水和污水开关显示的函数----发送请求指令
	async function setRainwaterCheckedFunc() {
		Taro.showLoading({
			title: "执行中..."
		})
		if (oneOrTwoSwitch) {
			if (oneSwichStatus) {
				console.log(111)
				await exeControlCommand({controlId: oneCancelSwitch})
					.then(res => {
						console.log(res)
						Taro.showModal({
							title: "提示",
							content: res.msg,
							success(result) {
								if (result.confirm) {
									Taro.hideLoading()
								} else if (result.cancel) {
								}
							}
						})
					})
					.catch(error => {
						Taro.hideLoading()
						console.log(error)
						Taro.showModal({
							title: "提示",
							content: error.msg,
							success(result) {
								if (result.confirm) {
									Taro.hideLoading()
								} else if (result.cancel) {
								}
							}
						})
					})
			} else {
				console.log(222)
				await exeControlCommand({controlId: oneOpenSwitch})
					.then(res => {
						console.log(res)
						Taro.showModal({
							title: "提示",
							content: res.msg,
							success(result) {
								if (result.confirm) {
									Taro.hideLoading()
								} else if (result.cancel) {
								}
							}
						})
					})
					.catch(error => {
						Taro.hideLoading()
						console.log(error)
						Taro.showModal({
							title: "提示",
							content: error.msg,
							success(result) {
								if (result.confirm) {
									Taro.hideLoading()
								} else if (result.cancel) {
								}
							}
						})
					})
				// Taro.hideLoading()
			}
		} else {
			if (rainwaterChecked) {
				exeControlCommand({controlId: rainwaterClose})
					.then(res => {
						exeControlCommand({controlId: sewageOpen})
							.then(() => {
								setRainwaterChecked(!rainwaterChecked)
								setSewageChecked(!sewageChecked)
							})
							.catch(err => {
								Taro.hideLoading()
								// instructErrorHintFunc()
								Taro.showModal({
									title: "提示",
									content: `${err.msg}`,
									success(result) {
										if (result.confirm) {
										} else if (result.cancel) {
										}
									}
								})
							})
					})
					.catch(err => {
						Taro.hideLoading()
						Taro.showModal({
							title: "提示",
							content: `${err.msg}`,
							success(result) {
								if (result.confirm) {
								} else if (result.cancel) {
								}
							}
						})
					})
			} else {
				exeControlCommand({controlId: sewageClose})
					.then(() => {
						setRainwaterChecked(!rainwaterChecked)
						setSewageChecked(!sewageChecked)
						exeControlCommand({controlId: rainwaterOpen})
							.then(() => {
								setRainwaterChecked(!rainwaterChecked)
								setSewageChecked(!sewageChecked)
							})
							.catch(err => {
								Taro.hideLoading()
								Taro.showModal({
									title: "提示",
									content: `${err.msg}`,
									success(result) {
										if (result.confirm) {
										} else if (result.cancel) {
										}
									}
								})
							})
					})
					.catch(err => {
						Taro.hideLoading()
						Taro.showModal({
							title: "提示",
							content: `${err.msg}`,
							success(result) {
								if (result.confirm) {
								} else if (result.cancel) {
								}
							}
						})
					})
			}
			// Taro.hideLoading()
		}
		// Taro.hideLoading()
	}

	return (
		<View className="container bg-xx_bg" style="overflow: scroll;">
			<View className="hanzi text-16 font-bold mt-23 mb-14 px-16">功能控制</View>
			<View className="hanzi text-14 text-xx_text mb-14 px-16">
				点击下面的按钮对设备发送相关指令，对设备进行远程操控
			</View>
			<View style="padding:6px 10px;overflow: scroll;">
				{compModuleData.map((list, index) => (
					<View style="margin-bottom:16px;padding-top:14px;border-radius:20px; overflow: auto;">
						<Text style="margin-left:14px;">{"模块" + (index + 1)}</Text>
						<Middlevare compDataList={list.list}></Middlevare>
					</View>
				))}
			</View>

			{/* <View className="p-16 grid grid-cols-2 gap-x-15 gap-y-16">
				{dataSource.map(controll => (
					<ControllBtn
						controll={controll}
						rainwaterChecked={rainwaterChecked}
						sewageChecked={sewageChecked}
						setRainwaterCheckedFunc={setRainwaterCheckedFunc}
						setSewageChecked={setSewageChecked}
						setRainwaterChecked={setRainwaterChecked}
						setOneSwitchStatus={setOneSwitchStatus}
						oneSwichStatus={oneSwichStatus}
						oneOrTwoSwitch={oneOrTwoSwitch}
						isSwitchOrBtn={isSwitchOrBtn}
						onlyOpenCardClick={onlyOpenCardClick}
					/>
				))}
			</View> */}
		</View>
	)
}
export default observer(Devcontroll)
